package com.epoch.platform.sys.userrole.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.ArrayUtils;

import com.epoch.base.annotation.ControllerBind;
import com.epoch.base.base.BaseController;
import com.epoch.base.exception.BusinessException;
import com.epoch.base.util.AjaxResult;
import com.epoch.platform.sys.role.dao.SysRole;
import com.epoch.platform.sys.user.dao.SysUser;
import com.epoch.platform.sys.userrole.dao.SysUserRole;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;

@ControllerBind(controllerKey = "/sys/userrole")
public class UserRoleController extends BaseController {
	
	private AjaxResult ajaxResult = new AjaxResult();

    public void index() {
    	List<Kv> sysRoleList = new ArrayList<Kv>();
        List<SysRole> enableRoleList = SysRole.dao.find(Db.getSqlPara("systemManage.findSysRoleForTreeByStatus", Kv.by("status", "ENABLE")));
        if (enableRoleList != null && !enableRoleList.isEmpty()) {
            for (SysRole role : enableRoleList) {
                Kv node = Kv.by("id", role.getStr(SysRole.ID)).set("name", role.getStr(SysRole.ROLE_NAME));
                String roleType = role.getStr(SysRole.ROLE_TYPE);
                if ("SYSTEM".equals(roleType)) {
                    sysRoleList.add(node);
                }
            }
        }
        this.setAttr("sysRoles", JsonKit.toJson(sysRoleList));
        render("/sys/userrole/sys_user_role.html");
    }
    
    public void findRoleUsersAjax() {
        Kv params = this.commonParams();
        String roleId = this.getPara("roleId");
        params.set("roleId", "'"+roleId+"'");
        int pageNumber = params.getInt("pageNumber");
        int pageSize = params.getInt("pageSize");
        SqlPara findSqlPara = Db.getSqlPara("systemManage.searchUserRoleByRoleId", params);
        SqlPara countSqlPara = Db.getSqlPara("systemManage.countUserRoleByRoleId", params);
        Page<SysUserRole> page = SysUserRole.dao.paginateByFullSql(pageNumber, pageSize, countSqlPara.getSql(), findSqlPara.getSql(), findSqlPara.getPara());
        this.renderJson(page);
    }
    
    public void edit() {
        this.keepPara("roleType", "roleId", "deptRole", "roleName");
        this.render("/sys/user/user_role_edit.html");
    }
    
    public void save() {
        String[] ids = getParaValues("ids[]");
        String roleId = getPara("roleId");
        try {
            if (ArrayUtils.isNotEmpty(ids)) {
            	List<SysUserRole> list = SysUserRole.dao.find("SELECT ur.id,ur.user_id FROM sys_user_role ur WHERE ur.role_id = ?", roleId);
                Set<String> userIdSet = new HashSet<String>();
                if (list != null) {
                    for (SysUserRole ur : list) {
                        userIdSet.add(ur.getStr(SysUserRole.USER_ID));
                    }
                }
                for (String id : ids) {
                    if (!userIdSet.contains(id)) {
                    	SysUserRole userRole = new SysUserRole();
                        userRole.set(SysUserRole.ROLE_ID, roleId);
                        userRole.set(SysUserRole.USER_ID, id);
                        userRole.save();
                    }
                }
            }
            ajaxResult.success("保存成功！");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.success("保存失败！");
        }
        renderJson(ajaxResult);
    }
    
    public void deleteSysRole() {
    	String[] ids = getParaValues("ids[]");
        try {
            if (ArrayUtils.isNotEmpty(ids)) {
            	for (String id : ids) {
            		SysUserRole.dao.deleteById(id);
				}
            }
            ajaxResult.success("保存成功！");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.success("保存失败！");
        }
        renderJson(ajaxResult);
    }
	public void updateAllocateAllSysRole() {
		Kv params = Kv.create();
		SqlPara sqlPara = Db.getSqlPara("systemManage.findSysUserList", params);
		List<SysUser> list = SysUser.dao.find(sqlPara);
		String roleId = getPara("roleId");
		try {
			Db.update("delete from sys_user_role where role_id = ?",roleId);
			for (SysUser sysUser : list) {
				SysUserRole sysRole = new SysUserRole();
				sysRole.set(SysUserRole.USER_ID, sysUser.getStr(SysUser.ID));
				sysRole.set(SysUserRole.ROLE_ID, roleId);
				sysRole.save();
			}
			ajaxResult.success("分配成功！");
		} catch (BusinessException e) {
			e.printStackTrace();
			ajaxResult.addError("分配失败！");
		}
		renderJson(ajaxResult);
		
	}
	
	public void updateRemoveAllSysRole	() {
		String roleId = getPara("roleId");
		try {
			Db.update("delete from sys_user_role where role_id = ?",roleId);
			ajaxResult.success("移除成功！");
		} catch (BusinessException e) {
			e.printStackTrace();
			ajaxResult.addError("移除成功！");
		}
		renderJson(ajaxResult);
	}
}
